package com.maple.serialport;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android_serialport_api.MyFunc;
import android_serialport_api.OnDataReceiveListener;
import android_serialport_api.SerialPortManager;

public class MainActivity extends Activity implements OnDataReceiveListener {

    EditText edit_content;
    SerialPortManager serialPortManager;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=findViewById(R.id.content);
        edit_content = findViewById(R.id.edit_content);
        serialPortManager = new SerialPortManager();
        serialPortManager.regist(this);
        open(null);
    }

    public void open(View view) {

        serialPortManager.openSerialPort("/dev/ttyS1", 9600);
    }


    public void send(View view) {

        String command = edit_content.getText().toString().trim();

        if (TextUtils.isEmpty(command)) {
            return;
        }
        byte[] sendContentBytes = command.getBytes();
        serialPortManager.putCommand(sendContentBytes);
    }

    private StringBuilder res = null;

    @Override
    public void onDataReceive(byte[] buffer) {
        /**二维码**/
//        String str = new String(buffer);
//        if (null == res) {
//            res = new StringBuilder();
//        }
//        res.append(str);
//
//        if (str.indexOf("\r\n") > 0) {
//            Log.i("QR", "QR_CODE_RESULT: " + res.toString());
//            //去除"\t|\r|\n"
//            Pattern p = Pattern.compile("\t|\r|\n");
//            Matcher m = p.matcher(res.toString());
//            final String resStr = m.replaceAll("");
//            Log.i("QR", "QR_CODE_RESULT_REPAIR: " + resStr);
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    textView.setText(resStr);
//                }
//            });
//        }

        /**IC卡**/
        String data = MyFunc.ByteArrToHex(buffer);
        final String cardID = data.trim().replace(" ", "");
        if (cardID.length() >= 8) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(cardID);
                }
            });

            Log.i("IC", "IC_CODE_RESULT_REPAIR: " + cardID);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialPortManager.close();
        serialPortManager.unregist(this);
    }
}
